<template>
  <div>
    <el-upload action="" class="avatar-uploader" v-bind="$attrs" :before-upload="beforeUpload">
      <img v-if="url" :src="url" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import { uploadFile } from '@/api'

export default {
  props: {
    url: String
  },
  methods: {
    // 上传之前: 获取file对象进行参数验证
    beforeUpload(file) {
      const formData = new FormData()
      formData.append('file', file)
      uploadFile(formData).then(res => {
        this.$emit('on-success', res.data.url)
      })
      return false
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 278px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 278px;
  height: 100px;
  display: block;
}
</style>

